package com.ajx.blog.service.impl;

import com.ajx.blog.entity.Admin;
import com.ajx.blog.entity.Roles;
import com.ajx.blog.mapper.AdminMapper;
import com.ajx.blog.mapper.RolesMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RolesMapper rolesMapper;

    @Override
    /**
     * @param {String} userName 登录账号
     * @return { UserDetails} UserDetails对象
     * 
     * @description: SpringSecurity权限框架返回一个UserDetails对象
     */
    public UserDetails loadUserByUsername(String userName) {
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("admin_name", userName);
        Admin admin = adminMapper.selectOne(qw);
        if (admin == null) {
            throw new UsernameNotFoundException("用户名错误");
        }
        QueryWrapper<Roles> qw1 = new QueryWrapper<>();
        qw1.inSql("id", "select roles from roles_admins where admins = " + admin.getAdminId());
        List<Roles> roleList = rolesMapper.selectList(qw1);
        admin.setRoles(roleList);
        return admin;
    }

}
